package com.zeyu.framework.tools.schedule.web;

import com.zeyu.framework.core.common.mapper.JsonMapper;
import com.zeyu.framework.core.persistence.Page;
import com.zeyu.framework.core.web.BaseController;
import com.zeyu.framework.core.web.Result;
import com.zeyu.framework.tools.schedule.entity.JobEntity;
import com.zeyu.framework.tools.schedule.entity.ScheduleHistory;
import com.zeyu.framework.tools.schedule.service.JobService;
import com.zeyu.framework.tools.schedule.service.ScheduleHistoryService;
import com.zeyu.framework.utils.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 任务调度Controller
 */
@Controller
@RequestMapping(value = "/tools/schedule/")
public class JobController extends BaseController {

    // ================================================================
    // Constants
    // ================================================================

    // ================================================================
    // Fields
    // ================================================================

    @Autowired
    private JobService jobService;

    @Autowired
    private ScheduleHistoryService scheduleHistoryService;

    // ================================================================
    // Constructors
    // ================================================================

    // ================================================================
    // Methods from/for super Interfaces or SuperClass
    // ================================================================

    // ================================================================
    // Public or Protected Methods
    // ================================================================

    /**
     * 任务列表页
     */
    @RequiresPermissions("tools:schedule:view")
    @RequestMapping(value = {"", "index"})
    public String index() {
        return "modules/tools/scheduleIndex";
    }

    /**
     * 任务表单页
     */
    @RequiresPermissions("tools:schedule:view")
    @RequestMapping(value = "form")
    public String form(String group, String name, Model model) {
        //  获取指定的group和name的信息
        model.addAttribute("entity", JsonMapper.toJsonString(jobService.getJobEntity(group, name)));
        return "modules/tools/scheduleForm";
    }

    /**
     * 任务历史列表页
     */
    @RequiresPermissions("tools:schedule:view")
    @RequestMapping(value = "history")
    public String history(String group, String name, Model model) {
        //  获取指定的group和name的信息
        model.addAttribute("entity", JsonMapper.toJsonString(jobService.getJobEntity(group, name)));
        return "modules/tools/scheduleHistory";
    }

    /**
     * 任务列表页
     */
    @RequiresPermissions("tools:schedule:view")
    @RequestMapping(value = "table")
    public String table(String group, Model model) {
        model.addAttribute("group", group);
        return "modules/tools/scheduleList";
    }

    /**
     * 任务列表获取
     */
    @RequiresPermissions("tools:schedule:edit")
    @RequestMapping(value = "list")
    @ResponseBody
    public Page<JobEntity> list(HttpServletRequest request) {
        Page<JobEntity> page = new Page<>(request);
        // 查询扩展
        String extraSearch = page.getDatatablesCriterias().getExtraSearch();
        // 转换
        JobEntity jobEntity = JsonMapper.getInstance().fromJson(extraSearch, JobEntity.class);
        if (jobEntity == null) {
            jobEntity = new JobEntity();
        }
        List<JobEntity> jobEntityList = jobService.find(jobEntity.getGroup());
        page.setCount(1);
        page.setList(jobEntityList);
        return page;
    }

    /**
     * 获取任务调度树
     */
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "treeData")
    public List<Map<String, Object>> treeData() {
        return jobService.treeData();
    }

    /**
     *
     */
    @RequiresPermissions("tools:schedule:edit")
    @ResponseBody
    @RequestMapping(value = "update")
    public Result update(String type, JobEntity entity) {

        Result result = new Result();
        if (MODE_DEMO) {
            result.setStatus(Result.ERROR);
            result.setMessage("演示模式，不允许操作!");
            return result;
        }

        JobEntity relEntity = jobService.getJobEntity(entity.getGroup(), entity.getName());
        relEntity.setStartDate(entity.getStartDate());
        relEntity.setEndDate(entity.getEndDate());
        // 判定是什么类型的触发器，然后对数据进行处理
        if (StringUtils.equals("1", type)) {
            relEntity.setUnitType(entity.getUnitType());
            relEntity.setInterval(entity.getInterval());
            relEntity.setCron("");
        } else {
            relEntity.setInterval(0);
            relEntity.setUnit(null);
            relEntity.setCron(entity.getCron());
        }
        relEntity.setDescription(entity.getDescription());
        relEntity.setHistory(entity.isHistory());

        boolean execute = true;
        try {
            jobService.addJob(relEntity);
        } catch (Exception e) {
            logger.error("更新任务失败", e);
            execute = false;
        }

        if (execute) {
            result.setStatus(Result.SUCCESS);
            result.setMessage("更新任务'" + entity.getName() + "'成功");
        } else {
            result.setStatus(Result.ERROR);
            result.setMessage("更新任务'" + entity.getName() + "'失败");
        }

        return result;
    }

    /**
     * 暂停任务
     */
    @ResponseBody
    @RequestMapping(value = "pause")
    public Result pause(String name, String group) {

        Result result = new Result();
        if (MODE_DEMO) {
            result.setStatus(Result.ERROR);
            result.setMessage("演示模式，不允许操作!");
            return result;
        }

        String[] names = name.split(",");
        String[] groups = group.split(",");
        boolean execute = true;
        for (int i = 0; i < names.length; i++) {
            try {

                JobEntity entity = jobService.getJobEntity(groups[i], names[i]);
                jobService.pauseJob(entity);

            } catch (Exception e) {
                logger.error("暂停任务失败", e);
                execute = false;
            }
        }

        if (execute) {
            result.setStatus(Result.SUCCESS);
            result.setMessage("暂停任务'" + name + "'成功");
        } else {
            result.setStatus(Result.ERROR);
            result.setMessage("暂停任务'" + name + "'失败");
        }

        return result;
    }

    /**
     * 恢复任务
     */
    @ResponseBody
    @RequestMapping(value = "resume")
    public Result resume(String name, String group) {

        Result result = new Result();
        if (MODE_DEMO) {
            result.setStatus(Result.ERROR);
            result.setMessage("演示模式，不允许操作!");
            return result;
        }

        String[] names = name.split(",");
        String[] groups = group.split(",");
        boolean execute = true;
        for (int i = 0; i < names.length; i++) {
            try {

                JobEntity entity = jobService.getJobEntity(groups[i], names[i]);
                jobService.resumeJob(entity);

            } catch (Exception e) {
                logger.error("恢复任务失败", e);
                execute = false;
            }
        }

        if (execute) {
            result.setStatus(Result.SUCCESS);
            result.setMessage("恢复任务'" + name + "'成功");
        } else {
            result.setStatus(Result.ERROR);
            result.setMessage("恢复任务'" + name + "'失败");
        }

        return result;
    }

    /**
     * 任务执行历史
     */
    @ResponseBody
    @RequestMapping(value = "historyList")
    public Page<ScheduleHistory> historyList(HttpServletRequest request) {

        Page<ScheduleHistory> page = new Page<>(request);

        // 查询扩展
        String extraSearch = page.getDatatablesCriterias().getExtraSearch();

        // 查询参数
        // 转换
        ScheduleHistory scheduleHistory = JsonMapper.getInstance().fromJson(extraSearch, ScheduleHistory.class);

        if (scheduleHistory == null) {
            scheduleHistory = new ScheduleHistory();
        }

        return  scheduleHistoryService.findPage(page, scheduleHistory);

    }

    // ================================================================
    // Getter & Setter
    // ================================================================

    // ================================================================
    // Private Methods
    // ================================================================

    // ================================================================
    // Inner or Anonymous Class
    // ================================================================

    // ================================================================
    // Test Methods
    // ================================================================
}
